package com.fredhat.tvshowrenamer.matcher;

import java.io.File;
import java.util.regex.*;

import com.fredhat.tvshowrenamer.Configuration;
import com.fredhat.tvshowrenamer.TVShow;
import com.fredhat.tvshowrenamer.TVShowEpisode;
import com.fredhat.tvshowrenamer.parser.TVParser;
import com.fredhat.tvshowrenamer.parser.tvcom.TVComParser;

public class SeasonMatcher extends AbstractMatcher {
	public SeasonMatcher(Configuration config) {
		super(config);
	}
	
	public TVShowEpisode matchingShowEpisode(TVShow tvShow, File file) {
		logger.debug("Checking for SeasonMatcher pattern match on file "+file.getName());
		String[] regexes = getConfiguration().getEpisodeRegexes();
		for(int i=0; i<regexes.length; i++) {
			logger.debug("Trying pattern "+regexes[i]);
			Pattern pattern = Pattern.compile(regexes[i]);
			Matcher matcher = pattern.matcher(file.getName());
			if (matcher.matches()) {
				int groupCount = matcher.groupCount();
				if (groupCount < 2) {
					logger.error("Pattern "+regexes[i]+" matches for show "+
							file.getName()+" but need at least two groups to "+
							"capture episode");
					continue;
				} else if (groupCount > 2) {
					logger.warn("Pattern "+regexes[i]+" has more than two groups.");
				}
				
				int season = 0;
				int episode = 0;
				try {
					season = Integer.parseInt(matcher.group(1));
				} catch (NumberFormatException e) {
					logger.error("Pattern "+regexes[i]+" matches but "+
							"group 1 contents are non-numeric");
					continue;
				}
				
				try {
					episode = Integer.parseInt(matcher.group(2));
				} catch (NumberFormatException e) {
					logger.error("Pattern "+regexes[i]+" matches but "+
							"group 2 contents are non-numeric");
					continue;
				}
				
				logger.debug("Found season and episode for "+file.getName()+
						" (S"+season+"E"+episode+")");
				
				TVParser parser = new TVComParser();
				return parser.getEpisode(tvShow, season, episode);
			}
		}
		
		logger.debug("No SeasonMatcher pattern found for "+file.getName());
		return null;
	}
}
